
import os
import shutil
import fnmatch
import pepe.p_filesystem.dfstats as dfs

def file_info(f):
    """Get information about file """
    #full_path = os.path.join(dataDir, f)
    file_info = dfs.dfstats(f, options=[])
    file_info['full_path'] = f
    file_info['file_name'] = string.split(f, '\x5C')[-1]

    #We don't want seconds in modified date_time
    file_info['mtime_iso'] = file_info['mtime_iso'][:-3]
    
    return file_info
    
    if 0: # procedure test - ok
        print file_info('examine_files.py')
        #print file_info(r'C:\AFT\backup\Cyrill_Rawdata\R01_BSIS_RU40_2010.dmp')
        '''
        {'Archive_name': 'R01_EKPO_AT00_2007to2010.dmp', 'mtime_iso': ' ... 
         'mtime_plain': '20101006120611', 'file_name': 'R01_EKPO_AT00_2 ... 
        h': 'R01_EKPO_AT00_2007to2010.dmp', 'size': 637952L}
        {'Archive_name': 'R01_BSIS_RU40_2010.dmp', 'mtime_iso': '2010-1 ... 
        e_plain': '20101005082624', 'file_name': 'R01_BSIS_RU40_2010.dm ...
        R01_BSIS_RU40_2010.dmp', 'size': 8716288L}
        '''

def delete_dir_contens(d):
    """Delete directory contens recursively
    
    We do not want to delete directory passed as parameter.
    Only its contens is to be deleted recursively.

    """
    for x in os.listdir(d):
        dx = d+'\x5C'+x
        if os.path.isdir(dx):
            # delete an entire directory tree
            # path must point to a directory
            shutil.rmtree(dx)
        if os.path.isfile(dx):
            os.remove(dx)

    if 0: # test procedure - ok
        delete_dir_contens(r'D:\viktor')


def files_list(dataDir):
    """Get list of files """
    return fslist(root=dataDir, patterns='*', recurse=True, return_folders=False)

    if 0: # procedure test - ok
        files = files_list(r'C:\AFT\pmfs\notepad2')
        for f in files:
            print f
        '''
        C:\AFT\pmfs\notepad2\License.txt
        C:\AFT\pmfs\notepad2\Notepad2.exe
        ...
        '''

def look_for_extension(filesDir, extensions):
    """Search recursivelly for file with given extension """
    r = False
    files = files_list(filesDir)
    for f in files:
        if os.path.splitext(f)[1] in extensions:
            return True
    return False


def fslist(root, patterns='*', recurse=True, return_folders=False):
    """

    #import pepe.p_filesystem.basic as pfb

    # Change this setting so that it finds the files (in twiki syntax) that
    # you want to convert to tiddlywiki syntax:
    #file_list = fslist('C:\A0_PRIV\EDOC', '*;')
    file_list = pfb.fslist(root='.', patterns='*', recurse=True, return_folders=False)

    for file_s in file_list:
        print file_s

    """

    # Expand patterns from semicolon-separated string to list
    pattern_list = patterns.split(';')

    # Collect input and output arguments into one bunch
    class Bunch:
        def __init__(self, **kwds): self.__dict__.update(kwds)
    arg = Bunch(recurse=recurse, 
                pattern_list=pattern_list,
                return_folders=return_folders,
                results=[])

    def visit(arg, dirname, files):
        # Append to arg.results all relevant files (and perhaps folders).
        for name in files:
            fullname = os.path.normpath(os.path.join(dirname, name))
            if arg.return_folders or os.path.isfile(fullname):
                for pattern in arg.pattern_list:
                    if fnmatch.fnmatch(name, pattern):
                        arg.results.append(fullname)
                        break
        # Block recursion if recursion was disallowed
        if not arg.recurse:
            files[:] = []

    os.path.walk(root, visit, arg)

    return arg.results

# License:
# This script makes use of the example on page 144 of the Python Cookbook, by 
# Robin Parmar and Alex Martelli, so it is under the same "modified Berkeley
# license" (see p. xix of that book).
#
# listFiles:
# Walk a directory tree, and obtain a list of all the files (and optionally
# all the directories) that match a certain pattern.
#
# The standard directory-tree function os.path.walk is powerful and flexible,
# but it can be confusing to beginners. This recipe dresses it up in a listFiles
# function that lets you choose the root folder, whether to recurse down through
# subfolders, the patterns to match, and whether to include folder names in the
# result list.
#
# The file patterns are case-insensitive but otherwise Linux-style, as supplied
# by the standard fnmatch module, which this recipe uses. To specify multiple
# patterns, join them with a semicolon. Note that this means that semicolons
# themselves can't be part of a pattern.
# For example, you can easilu get a list of all Python and HTML files in
# directory /tmp or any subdirectory thereof, using:
#   thefiles = listFiles('/tmp', '*.py;*.htm;*.html')
#

if __name__ == '__main__':

    file_list = fslist('C:\\', '*;', recurse=False)
    for file_s in file_list:
        print file_s

